package com.javakc.pms.logger.advice;

import com.javakc.pms.logger.annotation.LoggerOperation;
import com.javakc.pms.logger.entity.Logger;
import com.javakc.pms.logger.service.LoggerService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Lazy
public class LoggerAdvice {

    @Autowired
    private LoggerService loggerService;

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.javakc.pms.logger.annotation.LoggerOperation)")
    public void pointcut(){}

    /**
     * AOP拦截日志添加
     * @param point 连接点
     * @return 返回结果
     * @throws Throwable 异常
     */
    @Around("pointcut()")
    public Object logger(ProceedingJoinPoint point) throws Throwable {
        //开始时间
        long start=System.currentTimeMillis();
        Object object=point.proceed();
        //结束时间
        long end=System.currentTimeMillis();
        //获取注解类
        MethodSignature signature= (MethodSignature) point.getSignature();
        LoggerOperation annotation = signature.getMethod().getAnnotation(LoggerOperation.class);
        logger(end-start,annotation.module(),annotation.type().getValue(), annotation.message());
        return object;
    }

    /**
     * 日志添加
     * @param times 总耗时
     * @param module 模块
     * @param type 类型
     * @param message 消息
     */
    public void logger(long times,String module,String type,String message){

        //获取请求对象
        RequestAttributes requestAttributes= RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request=servletRequestAttributes.getRequest();

        Logger logger=new Logger();
        logger.setModule(module);
        logger.setType(type);
        logger.setMessage(message);
        logger.setRequestMethod(request.getMethod());
        logger.setRequestIpaddr(request.getRemoteAddr());
        logger.setRequestUrl(request.getRequestURI());
        logger.setExecuteTime(times);
        loggerService.saveOrUpdate(logger);
    }

}
